//
//  XMLWorkOrderParser.m
//
//  Created by Olof Millberg on 2010-03-23.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "XMLWorkOrderParser.h"

@implementation XMLWorkOrderParser

- (NSMutableArray*)parseXMLFile:(NSString *)pathToFile 
{
	// Convert the path to an URL.
    NSURL *xmlURL = [NSURL fileURLWithPath:pathToFile];
	
	// Release the parser if there already is one.
    if (workOrderParser)
        [workOrderParser release];
	
	// Initialize a new one with the URL.
    workOrderParser = [[NSXMLParser alloc] initWithContentsOfURL:xmlURL];
	
	// Set delegate to this.
    [workOrderParser setDelegate:self];
	
	// ???
    [workOrderParser setShouldResolveExternalEntities:YES];
	
	// Profit
	BOOL success = [workOrderParser parse]; 
	
	// We could check the return value here but for now we let the delegate handle any errors.
	
	// Return the work order list.
	return workOrders;
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
	
    if ([elementName isEqualToString:@"workorders"])
	{
        // Create a new work order list.
		if (!workOrders)
			workOrders = [[NSMutableArray alloc] init];
    }
	
    if ([elementName isEqualToString:@"workorder"])
	{
        // Create a new work order.
        currentWorkOrder = [[WorkOrder alloc] init];
		currentWorkOrder.employees = [NSMutableArray array];
		currentWorkOrder.contactPersons = [NSMutableArray array];
    }
	
	if ([elementName isEqualToString:@"address"])
	{
		currentWorkOrder.address = [[WOAddress alloc] init];
	}
	
	// Ugly workaround because foundCharacters isn't ignoring whitespaces for some reason.
	if (currentStringValue) 
	{
		[currentStringValue release];
		currentStringValue = nil;
	}
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string 
{
    if (!currentStringValue) 
	{
        // If there is no string we create a new one.
        currentStringValue = [[NSMutableString alloc] initWithString:string];
		return;
    }
	// Otherwise append.
    [currentStringValue appendString:string];
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName 
{
    // ignore root and "empty" elements
    if (([elementName isEqualToString:@"workorders"]) || ([elementName isEqualToString:@"address"]))
		return;
	
    if ([elementName isEqualToString:@"workorder"])
	{
		// Add the work order to the list.
        [workOrders addObject:currentWorkOrder];
		
        [currentWorkOrder release];
		currentWorkOrder = nil;
        return;
    }
	
	if ([elementName isEqualToString:@"workid"])
	{
		currentWorkOrder.workID = [currentStringValue stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
		return;
	}
	
	if ([elementName isEqualToString:@"date"])
	{
		// Convert to an NSDate object using a date formatter.
		NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
		[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
		currentWorkOrder.entryDate = [dateFormatter dateFromString:currentStringValue];
		return;
	}
	
	if ([elementName isEqualToString:@"street"])
	{
		currentWorkOrder.address.street = currentStringValue;
		return;
	}
	
	if ([elementName isEqualToString:@"postalcode"])
	{
		currentWorkOrder.address.zipCode = currentStringValue;
		return;
	}
	
	if ([elementName isEqualToString:@"city"])
	{
		currentWorkOrder.address.city = currentStringValue;
		return;
	}
	
	if ([elementName isEqualToString:@"contact"]) {
		[currentWorkOrder.contactPersons addObject:currentStringValue];
		return;
	}
	
	if ([elementName isEqualToString:@"assigned"])
	{
		[currentWorkOrder.employees addObject:currentStringValue];
		return;
	}
	
	// Granted the XML tag has the same name as the property this should work fine for the rest.
	[currentWorkOrder setValue:(id)currentStringValue forKey:elementName];
	
    [currentStringValue release];
    currentStringValue = nil;
}

// TODO: Error handling
/*
- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError {
    NSWindow *modWin = [self windowForSheet];
    if (!modWin) modWin = [NSApp mainWindow];
    NSAlert *parserAlert = [[NSAlert alloc] init];
    [parserAlert setMessageText:@"Parsing Error!"];
    [parserAlert setInformativeText:[NSString stringWithFormat:@"Error %i,
									 Description: %@, Line: %i, Column: %i", [parseError code],
									 [[parser parserError] localizedDescription], [parser lineNumber],
									 [parser columnNumber]]];
    [parserAlert addButtonWithTitle:@"OK"];
    [parserAlert beginSheetModalForWindow:modWin modalDelegate:self
						   didEndSelector:@selector(alertDidEnd:returnCode:contextInfo:)
							  contextInfo:nil];
    [parserAlert release];
}

- (void)alertDidEnd:(NSAlert *)alert returnCode:(int)returnCode contextInfo:(void *)contextInfo { }
 */

@end
